/**
 *    Copyright 2009-2021 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;

import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.builder.IncompleteElementException;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.parsing.PropertyParser;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * XML包含转换器,主要处理<include....>....</include>标签，如下：
 * <select id="selectById" resultMap="BaseResultMap">
 *         select
 *             my.*
 *         FROM
 *             sys_user my
 *         <include refid="test">
 *             <property name="testVal" value="1"/>
 *         </include>
 *     </select>
 *
 *     <sql id="test">
 *         <if test="${testVal} != null">
 *             WHERE my.id = ${testVal}
 *         </if>
 *     </sql>
 * @author Frank D. Martinez [mnesarco]
 */
public class XMLIncludeTransformer {
  /**
   * 配置信息
   */
  private final Configuration configuration;
  /**
   * mapper构建助手
   */
  private final MapperBuilderAssistant builderAssistant;

  public XMLIncludeTransformer(Configuration configuration, MapperBuilderAssistant builderAssistant) {
    this.configuration = configuration;
    this.builderAssistant = builderAssistant;
  }

  /**
   * 应用include
   * @param source 节点信息
   */
  public void applyIncludes(Node source) {
    // 存放变量信息
    Properties variablesContext = new Properties();
    // 从配置文件中获取变量信息
    Properties configurationVariables = configuration.getVariables();
    // 配置文件中获取的变量信息全部存放进入variablesContext
    Optional.ofNullable(configurationVariables).ifPresent(variablesContext::putAll);
    // 开始应用
    applyIncludes(source, variablesContext, false);
  }

  /**
   * Recursively apply includes through all SQL fragments.
   *
   * @param source 节点信息
   * @param variablesContext 参数内容
   * @param included 是否是include标签
   */
  private void applyIncludes(Node source, final Properties variablesContext, boolean included) {
    if ("include".equals(source.getNodeName())) {
      // 如果是include标签
      // 获取应用的节点，获取参数refid，getStringAttribute(source, "refid")
      // findSqlFragment 查找sql片段，封装成节点
      Node toInclude = findSqlFragment(getStringAttribute(source, "refid"), variablesContext);

      // 获取include的参数信息，类似下面的这个信息，处理里面的property
      // <select id="selectUsers" resultType="map">
      //  select
      //    <include refid="userColumns"><property name="alias" value="t1"/></include>,
      //    <include refid="userColumns"><property name="alias" value="t2"/></include>
      //  from some_table t1
      //    cross join some_table t2
      //</select>
      Properties toIncludeContext = getVariablesContext(source, variablesContext);
      // 重新解析include,处理include里面还有include的情况
      applyIncludes(toInclude, toIncludeContext, true);
      // 下面开始替换include标签，开始替换代码段
      if (toInclude.getOwnerDocument() != source.getOwnerDocument()) {
        toInclude = source.getOwnerDocument().importNode(toInclude, true);
      }
      source.getParentNode().replaceChild(toInclude, source);
      while (toInclude.hasChildNodes()) {
        toInclude.getParentNode().insertBefore(toInclude.getFirstChild(), toInclude);
      }
      // 移除原先的代码段
      toInclude.getParentNode().removeChild(toInclude);
    } else if (source.getNodeType() == Node.ELEMENT_NODE) {
      if (included && !variablesContext.isEmpty()) {
        // replace variables in attribute values
        NamedNodeMap attributes = source.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
          Node attr = attributes.item(i);
          attr.setNodeValue(PropertyParser.parse(attr.getNodeValue(), variablesContext));
        }
      }
      // 获取所有的子节点信息
      NodeList children = source.getChildNodes();
      for (int i = 0; i < children.getLength(); i++) {
        // 从新进行处理，这里面的标签，可能是<if>,<choose>等，不一定全是<include>
        applyIncludes(children.item(i), variablesContext, included);
      }
    } else if (included && (source.getNodeType() == Node.TEXT_NODE || source.getNodeType() == Node.CDATA_SECTION_NODE)
        && !variablesContext.isEmpty()) {
      // replace variables in text node
      source.setNodeValue(PropertyParser.parse(source.getNodeValue(), variablesContext));
    }
  }

  /**
   * 查找sql代码段
   * @param refid 引用ID
   * @param variables 参数信息
   * @return 返回节点信息
   */
  private Node findSqlFragment(String refid, Properties variables) {
    // 解析应用ID,这里主要处理${id}这样的动态id,如果不是动态的id怎么办，直接返回
    refid = PropertyParser.parse(refid, variables);
    // 引用ID增加空间描述
    refid = builderAssistant.applyCurrentNamespace(refid, true);
    try {
      // 获取引用的sqlId
      XNode nodeToInclude = configuration.getSqlFragments().get(refid);
      // 拷贝一个节点
      return nodeToInclude.getNode().cloneNode(true);
    } catch (IllegalArgumentException e) {
      throw new IncompleteElementException("Could not find SQL statement to include with refid '" + refid + "'", e);
    }
  }

  private String getStringAttribute(Node node, String name) {
    return node.getAttributes().getNamedItem(name).getNodeValue();
  }

  /**
   *
   * 从包含节点定义中读取占位符及其值
   *
   * @param node 包含的节点信息
   * @param inheritedVariablesContext 用于替换新变量值中的变量的当前上下文
   * @return include实例中的变量上下文（没有继承的值）
   */
  private Properties getVariablesContext(Node node, Properties inheritedVariablesContext) {
    // 申明参数
    Map<String, String> declaredProperties = null;
    // 获取子节点信息
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      Node n = children.item(i);
      if (n.getNodeType() == Node.ELEMENT_NODE) {
        // 处理类似下面的格式，include里面有<property>标签
        // <select id="selectUsers" resultType="map">
        //    select
        //    <include refid="userColumns"><property name="alias" value="t1"/></include>,
        //    <include refid="userColumns"><property name="alias" value="t2"/></include>
        //    from some_table t1
        //    cross join some_table t2
        // </select>
        String name = getStringAttribute(n, "name");
        // Replace variables inside
        // 解析出value
        String value = PropertyParser.parse(getStringAttribute(n, "value"), inheritedVariablesContext);
        if (declaredProperties == null) {
          declaredProperties = new HashMap<>();
        }
        // 设置新的参数
        if (declaredProperties.put(name, value) != null) {
          throw new BuilderException("Variable " + name + " defined twice in the same include definition");
        }
      }
    }
    // 设置新的参数信息
    if (declaredProperties == null) {
      return inheritedVariablesContext;
    } else {
      Properties newProperties = new Properties();
      newProperties.putAll(inheritedVariablesContext);
      newProperties.putAll(declaredProperties);
      return newProperties;
    }
  }
}
